// 新建文件夹
import React, { useEffect, useState } from 'react';
import { Card, Form, Input, Modal, Tree } from 'antd';
import FormItem from 'antd/lib/form/FormItem';
import { createAnalyseCategory, saveResourcePermission, selectOrgPosWithEmpTree, getResourcePermission, updateAnalyseCategory } from 'src/services/AnalyseManage';
import styles from '../index.module.scss';
import { /*getResourceIdByPath,*/ mapTreeData } from 'src/libs/utils';
import { connect } from 'react-redux';

const AddNewFolder = ( props: any ) => {
	const [ form ] = Form.useForm();
	const { modalVisible, onSuccess, onCancel, actionType } = props;
	const [ treeData, setTreeData ] = useState( [] );
	const [ editTreeData, setEditTreeData ] = useState( [] );
	const [ viewUserList, setViewUserList ] = useState( [] );
	const [ editUserList, setEditUserList ] = useState( [] );
	// const [ selectedViewKeys, setSelectedViewKeys ] = useState( [] );
	// const [ selectedEditKeys, setSelectedEditKeys ] = useState( [] );

	const getTreeData = async( roleType?: Array<string> ) => {
		const data = {
			type: 'ORGANIZATION',
			roleType
		};
		const res = await selectOrgPosWithEmpTree( data );
		if ( res.data.data ) {
			let treeData = res.data.data.map( org => mapTreeData( org ) );
			if ( roleType ) {
				setEditTreeData( treeData );
			} else {
				setTreeData( treeData );
			}
			// console.log( treeData );
		}
	};

	const onCheckViewUser = ( checkedKeys, info ) => {
		const data = info.checkedNodes.filter( t => t.type === 'USER' ).map( s => s.id );
		setViewUserList( data );
		form.setFieldsValue( { viewAuth: data } );
		// console.log( data );
	};

	const onCheckEditUser = ( checkedKeys, info ) => {
		const data = info.checkedNodes.filter( t => t.type === 'USER' ).map( s => s.id );
		setEditUserList( data );
		form.setFieldsValue( { editAuth: data } );
	};

	const getPermission = async() => {
		const data = {
			'id': props.initialValues.id,
			'resourceType': 'category'
		};
		const res = await getResourcePermission( data );
		// eslint-disable-next-line no-empty
		if ( res.data ) {
			setViewUserList( res.data.data.viewUserList );
			setEditUserList( res.data.data.editUserList );
			// console.log( res.data.data.viewUserList, res.data.data.editUserList );
		}
	};

	const savePermission = async( id ) => {
		// console.log( id, editUserList, viewUserList );
		const data = {
			editUserList,
			id,
			resourceType: 'category',
			viewUserList
		};
		const res = await saveResourcePermission( data );
		if ( res.data && res.data.success ) {
			onSuccess( id );
		}
	};

	useEffect( () => {
		getTreeData();
		getTreeData( [ 'editor' ] );
		if ( props.initialValues.id ) {
			getPermission();
		}
	// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [] );

	const okHandle = async () => {
		form.setFieldsValue( { editAuth: editUserList, viewAuth: viewUserList } );
		form.validateFields()
			.then( async ( values: any ) => {

				let response;
				const { name, des } = values;
				// const resource = getResourceIdByPath( props.menu, '/analyseManage/myAnalysis' );
				let data = {
					name, 
					des, 
					type: actionType === 'ADD' ? 'CUSTOMER' : undefined, 
					parentId: actionType === 'ADD' ? '0' /*resource.resourceId*/ : undefined,
					id: actionType === 'EDIT' ? props.initialValues.id : undefined
				};
				if ( actionType === 'ADD' ) {
					response = await createAnalyseCategory( data );
					
				} else if ( actionType === 'EDIT' ) {
					response = await updateAnalyseCategory( data );
				}
				if ( response.data && response.data.success ) {
					savePermission( response.data.data.id );
				}
			} )
			.catch( errorInfo => {
				// console.log( errorInfo );
				// form.resetFields();
			} );
	};

	return (
		<Modal
			destroyOnClose
			title='添加文件夹'
			visible={modalVisible}
			onCancel={onCancel}
			onOk={okHandle}
			width="800px"
			okText='确定'
			cancelText='取消'
			className={styles.analysis_addfolder}
		>
			<Form
				preserve={false}
				layout="horizontal" form={form}
				initialValues={props.initialValues}
				labelCol={{ span: 4 }}>
				<FormItem
					label="名称" name="name" labelCol={{ span: 4 }}
					rules={[ { required: true, message: '不能为空！' } ]}>
					<Input placeholder="编码不能为空，且不可重复" style={{ width: '300px' }}/>
				</FormItem>
				<FormItem
					label="描述" name="des" labelCol={{ span: 4 }}>
					<Input style={{ width: '300px' }}/>
				</FormItem>
				<Form.Item label="可见权限" name="viewAuth"
					rules={[ { required: true, message: '不能为空！' } ]}>
					<Card style={{ width: 300 }}>
						<Tree
							checkable
							checkedKeys={viewUserList}
							treeData={treeData}
							onCheck={onCheckViewUser}
						/>
					</Card>
				</Form.Item>
				<Form.Item label="编辑权限" name="editAuth"
					rules={[ { required: true, message: '不能为空！' } ]}>
					<Card style={{ width: 300 }}>
						<Tree
							checkable
							checkedKeys={editUserList}
							treeData={editTreeData}
							onCheck={onCheckEditUser}
						/>
					</Card>
				</Form.Item>
			</Form>
		</Modal>
	);
};

//	映射state到当前组件
const mapStateToProps = ( state ) => {
	return {
		menu: state.menu
	};
};

export default React.memo( connect( mapStateToProps )( AddNewFolder ) );
